<template>
  <a-card :bordered="false">
    <div class="table-operator" style="display: flex; justify-content: space-between">
      <a-button style="margin-left: 8px" type="primary" icon="branches" @click="showStatistics">提取</a-button>
      <!-- <a-button type="primary" icon="redo" @click="getDataList()">刷新</a-button> -->
      <!-- <a-button style="margin-left: 8px;" type="primary" icon="line-chart" @click="showStatistics">提取</a-button> -->
      <a-form layout="inline">
        <a-row>
          <a-col :md="24" :sm="24">
            <!-- <a-input
              style="width: 150px"
              v-model="queryParam.keyword"
              placeholder="请输入购货方名称"
              @keydown.enter="getDataList"
            /> -->
            <searchTip
              v-model="queryParam.keyword"
              style="width: 150px; display: inline-block"
              placeholder="请输入购货方名称"
              :list="searchTipResultList"
              @enterKeyDown="getDataList"
              @change="toGetSearchTipList"
              @blur="keywordBlurFun"
              @select="selectSearchTipFun"
            />
            <a-select
              style="width: 100px; margin-left: 8px"
              v-model="selectTime"
              @change="changeTime"
              name="radioGroup"
              :default-value="0"
            >
              <a-select-option :value="index" v-for="(i, index) in ['一个月', '三个月', '六个月', '自定义']" :key="i">
                {{ i }}
              </a-select-option>
            </a-select>
            <a-range-picker style="margin-left: 8px; width: 220px" :disabled="timeDisabled" v-model="time" />
            <a-button
              style="margin-left: 8px"
              type="primary"
              @click="
                () => {
                  this.pagination.current = 1
                  this.getDataList()
                }
              "
              >查询
            </a-button>
            <a-button @click="repossess">重置 </a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-page-search-wrapper">
      <!-- <a-form layout="inline">
                <a-row :gutter="10">
                    <a-col :md="4" :sm="24">
                        <a-form-item label="查询类别">
                            <a-select allowClear v-model="queryParam.Condition">
                                <a-select-option key="TicketbuyerName">客户名称</a-select-option>
                                <a-select-option key="Invoicenumber">发票号码</a-select-option>
                                <a-select-option key="Invoicecode">发票代码</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="4" :sm="24">
                        <a-form-item>
                            <a-input v-model="queryParam.Keyword" placeholder="关键字" @keydown.enter="getDataList" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                        <a-button type="primary" @click="() => {
                            this.pagination.current = 1
                            this.getDataList()
                        }">查询</a-button>
                        <a-button style="margin-left: 8px" @click="repossess">重置</a-button>
                    </a-col>
                </a-row>
            </a-form> -->
    </div>

    <a-table
      ref="table"
      :scroll="{ y: 530, x: 1330 }"
      :columns="columns"
      :rowKey="(row, index) => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :bordered="true"
      size="small"
    >
      <span slot="ApplicantTime" slot-scope="ApplicantTime">{{ timeFormat(ApplicantTime) }}</span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleEdit(record.Id)">详情</a>
        </template>
      </span>
    </a-table>
    <a-modal :title="'提取异常发票'" width="300px" :footer="''" :visible="visible">
      <a-range-picker v-model="timer" />
      <div v-show="showSchedule" style="display: flex; margin-top: 20px; flex-direction: column; align-items: center">
        <a-progress :percent="percent" />
        <p style="text-align: center; margin-top: 20px">当前进度：{{ now }}/{{ totalAll }}</p>
      </div>
      <div style="display: flex; justify-content: center; align-items: center">
        <a-button
          v-if="cancelButton == 'a'"
          style="margin: 50px 0 20px 0; width: 100px"
          type="primary"
          @click="
            () => {
              this.getDataList()
              this.visible = false
              this.cancelButton = false
              this.showSchedule = false
              this.cancelButton == 'b'
            }
          "
          >完成</a-button
        >
        <a-button
          v-else
          :loading="cancelButton == 'c'"
          style="margin: 20px 0 20px 0; width: 100px"
          type="primary"
          @click="handleOk"
          >提取{{ cancelButton == 'c' ? '中' : '' }}</a-button
        >
        <a-button
          v-if="cancelButton == 'b'"
          style="margin: 20px 0 20px 20px; width: 100px"
          type="primary"
          @click="
            () => {
              this.visible = false
              this.cancelButton = false
              this.showSchedule = false
              this.cancelButton == 'b'
            }
          "
          >关闭</a-button
        >
      </div>
    </a-modal>
    <!-- <edit-form ref="editForm" :parentObj="this"></edit-form> -->
  </a-card>
</template>

<script>
import moment from 'moment'
import searchTip from '@/components/components/SearchTip.vue'

// import EditForm from './EditForm'
const columns = [
  { title: '申请时间', dataIndex: 'ApplicantTime', width: '100px', scopedSlots: { customRender: 'ApplicantTime' } },
  { title: '发票号码', dataIndex: 'Invoicenumber', width: '150px' },
  { title: '发票代码', dataIndex: 'Invoicecode', width: '150px' },
  { title: '购货方', dataIndex: 'TicketbuyerName', width: '300px' },
  { title: '金额', dataIndex: 'InvoiceAmount', width: '100px', align: 'right' },
  { title: '申请人', dataIndex: 'ApplicantName', width: '100px' },
  { title: '异常说明', dataIndex: 'Remark', width: '300px' },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'left',
    fixed: 'right',
    width: '80px',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  components: {
    searchTip,
    // EditForm
  },
  mounted() {
    this.timer = [
      this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1)),
      this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0)),
    ]
    this.time = [
      this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1)),
      this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0)),
    ]
    this.getDataList()
  },
  data() {
    return {
      data: [],
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true,
      },
      filters: {},
      sorter: { field: 'dDate', order: 'desc' },
      loading: false,
      columns,
      confirmLoading: false,
      queryParam: { Condition: 'TicketbuyerName' },
      selectedRowKeys: [],
      visible: false,
      percent: 0,
      // time: [],
      totalAll: 0,
      timer: [],
      now: 0,
      showSchedule: false,
      timeDisabled: true,
      selectTime: 0,
      cancelButton: 'b', //  a = 提取   b = 提取中   c =完成
      time: [
        moment(new Date(new Date().getFullYear(), new Date().getMonth(), 1)),
        moment(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0)),
      ],
      searchTipResultList: [],
    }
  },
  methods: {
    //重置
    repossess() {
      this.queryParam = { Condition: 'TicketbuyerName' }
      this.changeTime(0)
      this.getDataList()
    },
    //分页
    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.getDataList()
    },
    changeTime(e) {
      this.timeDisabled = true
      this.time = []
      this.selectTime = e
      switch (e) {
        case 0:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 1:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 2, 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 2:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 5, 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 3:
          this.timeDisabled = false
          break
      }
    },
    //获取列表数据
    getDataList() {
      this.searchTipResultList = [] //清空搜索提示列表
      this.selectedRowKeys = []
      this.loading = true
      this.$http
        .post('/InvoiceManagement/v_abnormalinvoice/GetDataList', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: 'id',
          SortType: 'desc',
          Search: {
            ...this.queryParam,
            StartTime: this.time[0] ? this.timeFormat(this.time[0]) : '',
            EndTime: this.time[1] ? this.timeFormat(this.time[1]) : '',
          },
        })
        .then((resJson) => {
          this.loading = false
          this.data = resJson.Data
          this.data.forEach((item, index) => {
            item.Amountincludingtax = this.$options.filters.NumberFormats(item.Amountincludingtax)
            item.InvoiceAmount = this.$options.filters.NumberFormats(item.InvoiceAmount)
            item.Remark = item.Remark ? `出库单 ${item.Remark} 已删除` : item.Remark
          })
          if (this.data) {
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    //提取
    async handleOk() {
      this.showSchedule = true
      this.cancelButton = 'c'
      try {
        let rows = 50

        let data = await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/ObtainDeliveryByCount', {
          Search: {
            Startdata: this.timeFormat(this.timer[0]),
            Enddata: this.timeFormat(this.timer[1]),
          },
        })
        this.totalAll = data.Data
        let percentEach = Number.isInteger(this.totalAll / rows)
          ? this.totalAll / rows
          : parseInt(this.totalAll / rows) + 1
        for (let i = 0; i < percentEach; i++) {
          this.now = i * rows
          this.percent = (100 / percentEach) * i
          let newData = await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/ObtainDeliveryList', {
            PageIndex: i + 1,
            PageRows: rows,
            SortField: 'OutboundOrder',
            SortType: 'desc',
            Search: {
              Startdata: this.timeFormat(this.timer[0]),
              Enddata: this.timeFormat(this.timer[1]),
            },
          })
          let arr = []
          newData.Data.forEach((item) => {
            arr.push(item.OutboundOrder)
          })
          await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/OperatingTheoutboundOrder', { codes: arr })
        }
        this.confirmLoading = false
        this.percent = 100
        this.now = this.totalAll
        this.cancelButton = 'a'
      } catch (err) {
        this.$message.error(err)
      }
    },
    showStatistics() {
      this.visible = true
      this.cancelButton = 'b'
    },
    // 详情
    handleEdit(id) {
      this.$refs.editForm.openForm(id)
    },
    timeFormat(val) {
      // 时间格式化函数
      return moment(val).format('YYYY-MM-DD')
    },

    async toGetSearchTipList(e) {
      this.searchTipResultList = []
      this.queryParam.keyword = e
      if (!this.queryParam.keyword) {
        return
      }
      await this.$httpp
        .post('/InvoiceManagement/v_abnormalinvoice/GetDataList', {
          PageIndex: 1,
          PageRows: 50,
          SortField: 'id',
          SortType: 'desc',
          Search: {
            ...this.queryParam,
            StartTime: this.time[0] ? this.timeFormat(this.time[0]) : '',
            EndTime: this.time[1] ? this.timeFormat(this.time[1]) : '',
          },
        })
        .then((resJson) => {
          if (resJson.Success && this.queryParam.keyword) {
            this.searchTipResultList = resJson.Data.map((e) => e.TicketbuyerName).slice(0, 10)
          } else {
            this.searchTipResultList = []
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    selectSearchTipFun(text) {
      this.queryParam.keyword = text
      this.searchTipResultList = []
      this.getDataList()
    },

    keywordBlurFun() {
      this.searchTipResultList = []
    },
  },
}
</script>
<style scoped>
::v-deep .ant-modal-close-x {
  display: none;
}

/deep/ .ant-table-thead > tr > th {
  /* background: #fff; */
}
</style>
